﻿/********************************************************
 * 类名： InitPayBLL.cs
 * 功能： 付款单管理数据层
 *   ver	变更日		作者			变更内容
 * ────────────────────────────────────────
 *   V01.0	2014-02-08	李波			初版
 *
 * Copyright (c) 2013，李波版权所有
 ********************************************************/
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using PSS.Entity.FundManage;
using PSS.Utility;

namespace PSS.DAL.FundManage
{
    public class InitPayDAL : DbHelperBase
    {
        public bool AddInitPay(InitPayEntity model)
        {
            var result = false;
            var strSql = new StringBuilder();
            strSql.Append(" INSERT INTO [PSS_InitPay]([InitPayId],[SinglePaymentNo],[SinglePaymentDate],[VendorId],[Remark]) ");
            strSql.Append(" VALUES(@InitPayId,@SinglePaymentNo,@SinglePaymentDate,@VendorId,@Remark) ");
            using (var cmd = Db.GetSqlStringCommond(strSql.ToString()))
            {
                try
                {
                    Db.AddInParameter(cmd, "@InitPayId", model.InitPayId);
                    Db.AddInParameter(cmd, "@SinglePaymentNo", model.SinglePaymentNo);
                    Db.AddInParameter(cmd, "@VendorId", model.VendorId);
                    Db.AddInParameter(cmd, "@SinglePaymentDate", model.SinglePaymentDate);
                    Db.AddInParameter(cmd, "@Remark", model.Remark);
                    result = Db.ExecuteNonQuery(cmd) > 0;
                }
                catch (Exception ex)
                {
                    EventsLog.WriteLog("ErrorInfo" + ex.Message);
                }
            }
            return result;
        }

        public void AddInitPayDetail(List<InitPayDetailEntity> list)
        {
            var conn = Db.GetConnection() as SqlConnection;
            if (conn == null)
            {
                throw new InvalidOperationException("No Valid Database Connection!");
            }
            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
            }
            using (var bcp = new SqlBulkCopy(conn))
            {
                var mapPayDetailId =
                    new SqlBulkCopyColumnMapping("PayDetailId", "PayDetailId");
                bcp.ColumnMappings.Add(mapPayDetailId);

                var mapInitPayId =
                    new SqlBulkCopyColumnMapping("InitPayId", "InitPayId");
                bcp.ColumnMappings.Add(mapInitPayId);

                var mapAccountId =
                    new SqlBulkCopyColumnMapping("AccountId", "AccountId");
                bcp.ColumnMappings.Add(mapAccountId);

                var mapPayMoney =
                    new SqlBulkCopyColumnMapping("PayMoney", "PayMoney");
                bcp.ColumnMappings.Add(mapPayMoney);

                var mapSCategoryId =
                   new SqlBulkCopyColumnMapping("SCategoryId", "SCategoryId");
                bcp.ColumnMappings.Add(mapSCategoryId);

                var mapSettleNo =
                   new SqlBulkCopyColumnMapping("SettleNo", "SettleNo");
                bcp.ColumnMappings.Add(mapSettleNo);

                var mapRemark =
                   new SqlBulkCopyColumnMapping("Remark", "Remark");
                bcp.ColumnMappings.Add(mapRemark);

                bcp.DestinationTableName = "PSS_InitPayDetail";

                try
                {
                    bcp.WriteToServer(Collection.ToDataTable(list));
                }
                catch (Exception ex)
                {
                    EventsLog.WriteLog("ErrorInfo" + ex.Message);
                }
                finally
                {
                    if (conn.State != ConnectionState.Closed)
                        conn.Close();
                }
            }
        }

        public int GetTotal(InitPayQcEntity qcmodel)
        {
            var strSql = new StringBuilder();
            strSql.Append(" SELECT COUNT(*) AS [Total] FROM PSS_InitPay AS A  ");
            strSql.Append(" LEFT JOIN (SELECT InitPayId,SUM(PayMoney) AS TotalPayMoney FROM PSS_InitPayDetail GROUP BY InitPayId)AS B ON A.InitPayId=B.InitPayId ");
            strSql.Append(" INNER JOIN PSS_Vendor AS C ON A.VendorId=C.VendorId ");
            strSql.Append(" WHERE 1=1 ");
            if (!string.IsNullOrEmpty(qcmodel.SinglePaymentNo))
            {
                strSql.Append(" AND A.SinglePaymentNo LIKE '%" + qcmodel.SinglePaymentNo + "%' ");
            }
            if (!string.IsNullOrEmpty(qcmodel.VendorId))
            {
                strSql.Append(" AND A.VendorId=@VendorId ");
            }
            if (!string.IsNullOrEmpty(qcmodel.SinglePaymentDateFrom))
            {
                strSql.Append(" AND A.SinglePaymentDate >=@SSinglePaymentDate");
            }
            if (!string.IsNullOrEmpty(qcmodel.SinglePaymentDateEnd))
            {
                strSql.Append(" AND A.SinglePaymentDate <=@ESinglePaymentDate");
            }
            var count = 0;
            using (var cmd = Db.GetSqlStringCommond(strSql.ToString()))
            {
                try
                {
                    if (!string.IsNullOrEmpty(qcmodel.VendorId))
                    {
                        Db.AddInParameter(cmd, "@VendorId", DbType.Guid, new Guid(qcmodel.VendorId));
                    }
                    if (!string.IsNullOrEmpty(qcmodel.SinglePaymentDateFrom))
                    {
                        Db.AddInParameter(cmd, "@SSinglePaymentDate", DbType.DateTime, Convert.ToDateTime(qcmodel.SinglePaymentDateFrom));
                    }
                    if (!string.IsNullOrEmpty(qcmodel.SinglePaymentDateEnd))
                    {
                        Db.AddInParameter(cmd, "@ESinglePaymentDate", DbType.DateTime, Convert.ToDateTime(qcmodel.SinglePaymentDateEnd));
                    }
                    using (IDataReader reader = Db.ExecuteReader(cmd))
                    {
                        if (reader.Read())
                        {
                            count = Convert.ToInt32(reader["Total"]);
                        }
                    }
                }
                catch (Exception ex)
                {
                    EventsLog.WriteLog("ErrorInfo" + ex.Message);
                }
                return count;
            }
        }

        public IList<InitPayEntity> GetInitPayList(InitPayQcEntity qcmodel)
        {
            var list = new List<InitPayEntity>();
            var strSql = new StringBuilder();
            object obj = DBNull.Value;
            var start = qcmodel.PageSize * qcmodel.PageIndex + 1;
            var end = qcmodel.PageSize + start - 1;
            strSql.Append(" SELECT T.* FROM( ");
            strSql.Append(" SELECT row_number() over (order by A.SinglePaymentNo desc) AS idx,A.InitPayId,A.SinglePaymentDate,A.SinglePaymentNo,C.VendorName,B.TotalPayMoney,A.Remark FROM PSS_InitPay AS A  ");
            strSql.Append(" LEFT JOIN (SELECT InitPayId,SUM(PayMoney) AS TotalPayMoney FROM PSS_InitPayDetail GROUP BY InitPayId)AS B ON A.InitPayId=B.InitPayId ");
            strSql.Append(" INNER JOIN PSS_Vendor AS C ON A.VendorId=C.VendorId ");
            strSql.Append(" WHERE 1=1 ");
            if (!string.IsNullOrEmpty(qcmodel.SinglePaymentNo))
            {
                strSql.Append(" AND A.SinglePaymentNo LIKE '%" + qcmodel.SinglePaymentNo + "%' ");
            }
            if (!string.IsNullOrEmpty(qcmodel.VendorId))
            {
                strSql.Append(" AND A.VendorId=@VendorId ");
            }
            if (!string.IsNullOrEmpty(qcmodel.SinglePaymentDateFrom))
            {
                strSql.Append(" AND A.SinglePaymentDate >=@SSinglePaymentDate");
            }
            if (!string.IsNullOrEmpty(qcmodel.SinglePaymentDateEnd))
            {
                strSql.Append(" AND A.SinglePaymentDate <=@ESinglePaymentDate");
            }
            strSql.Append(") AS T ");
            strSql.Append(" Where T.idx between " + start + " and " + end);
            if (qcmodel.SortField != "" && qcmodel.SortOrder != "")
            {
                strSql.Append(" Order by " + qcmodel.SortField + " " + qcmodel.SortOrder);
            }
            using (var cmd = Db.GetSqlStringCommond(strSql.ToString()))
            {
                try
                {
                    if (!string.IsNullOrEmpty(qcmodel.VendorId))
                    {
                        Db.AddInParameter(cmd, "@VendorId", DbType.Guid, new Guid(qcmodel.VendorId));
                    }
                    if (!string.IsNullOrEmpty(qcmodel.SinglePaymentDateFrom))
                    {
                        Db.AddInParameter(cmd, "@SSinglePaymentDate", DbType.DateTime, Convert.ToDateTime(qcmodel.SinglePaymentDateFrom));
                    }
                    if (!string.IsNullOrEmpty(qcmodel.SinglePaymentDateEnd))
                    {
                        Db.AddInParameter(cmd, "@ESinglePaymentDate", DbType.DateTime, Convert.ToDateTime(qcmodel.SinglePaymentDateEnd));
                    }
                    using (IDataReader reader = Db.ExecuteReader(cmd))
                    {
                        while (reader.Read())
                        {
                            var model = new InitPayEntity();
                            if (reader["InitPayId"] != DBNull.Value)
                                model.InitPayId = new Guid(reader["InitPayId"].ToString());
                            if (reader["SinglePaymentDate"] != DBNull.Value)
                                model.SinglePaymentDate = Convert.ToDateTime(reader["SinglePaymentDate"].ToString());
                            model.SinglePaymentNo = reader["SinglePaymentNo"] == obj ? null : Convert.ToString(reader["SinglePaymentNo"]);
                            model.VendorName = reader["VendorName"] == obj ? null : Convert.ToString(reader["VendorName"]);
                            if (reader["TotalPayMoney"] != DBNull.Value)
                                model.TotalPayMoney = Convert.ToDecimal(reader["TotalPayMoney"].ToString());
                            model.Remark = reader["Remark"] == obj ? null : Convert.ToString(reader["Remark"]);
                            list.Add(model);
                        }
                    }
                }
                catch (Exception ex)
                {
                    EventsLog.WriteLog("ErrorInfo" + ex.Message);
                }
            }
            return list;
        }

        public InitPayEntity GetInitPayInfo(string id)
        {
            var model = new InitPayEntity();
            object obj = DBNull.Value;
            var strSql = new StringBuilder();
            strSql.Append(" SELECT [InitPayId],[SinglePaymentNo],[SinglePaymentDate],[VendorId],[Remark] ");
            strSql.Append(" FROM [PSS_InitPay] where InitPayId=@InitPayId ");
            using (var cmd = Db.GetSqlStringCommond(strSql.ToString()))
            {
                try
                {
                    Db.AddInParameter(cmd, "@InitPayId", id);
                    using (IDataReader reader = Db.ExecuteReader(cmd))
                    {
                        if (reader.Read())
                        {
                            if (reader["InitPayId"] != DBNull.Value)
                                model.InitPayId = new Guid(reader["InitPayId"].ToString());
                            if (reader["VendorId"] != DBNull.Value)
                                model.VendorId = new Guid(reader["VendorId"].ToString());
                            if (reader["SinglePaymentDate"] != DBNull.Value)
                                model.SinglePaymentDate = Convert.ToDateTime(reader["SinglePaymentDate"].ToString());
                            model.SinglePaymentNo = reader["SinglePaymentNo"] == obj ? null : Convert.ToString(reader["SinglePaymentNo"]);
                            model.Remark = reader["Remark"] == obj ? null : Convert.ToString(reader["Remark"]);
                        }
                    }
                }
                catch (Exception ex)
                {
                    EventsLog.WriteLog("ErrorInfo" + ex.Message);
                }
                return model;
            }
        }

        public IList<InitPayDetailEntity> GetInitPayDetailList(InitPayDetailQcEntity qcmodel)
        {
            var list = new List<InitPayDetailEntity>();
            var strSql = new StringBuilder();
            object obj = DBNull.Value;
            strSql.Append(" SELECT A.PayDetailId,A.InitPayId,A.AccountId,B.AccountCode,B.AccountName,A.PayMoney,A.SCategoryId,C.SCategoryName,A.SettleNo,A.Remark FROM PSS_InitPayDetail AS A   ");
            strSql.Append(" LEFT JOIN PSS_Account AS B ON A.AccountId=B.AccountId  ");
            strSql.Append(" LEFT JOIN PSS_SettlementCategory AS C ON A.SCategoryId=C.SCategoryId ");
            strSql.Append(" WHERE A.[InitPayId]=@InitPayId ");
            strSql.Append(" ORDER BY A.CreateTime ");
            using (var cmd = Db.GetSqlStringCommond(strSql.ToString()))
            {
                try
                {
                    Db.AddInParameter(cmd, "@InitPayId", qcmodel.InitPayId);
                    using (IDataReader reader = Db.ExecuteReader(cmd))
                    {
                        while (reader.Read())
                        {
                            var model = new InitPayDetailEntity();
                            if (reader["PayDetailId"] != DBNull.Value)
                                model.PayDetailId = new Guid(reader["PayDetailId"].ToString());
                            if (reader["InitPayId"] != DBNull.Value)
                                model.InitPayId = new Guid(reader["InitPayId"].ToString());
                            if (reader["AccountId"] != DBNull.Value)
                                model.AccountId = new Guid(reader["AccountId"].ToString());
                            model.AccountCode = reader["AccountCode"] == obj ? null : Convert.ToString(reader["AccountCode"]);
                            model.AccountName = reader["AccountName"] == obj ? null : Convert.ToString(reader["AccountName"]);
                            if (reader["PayMoney"] != DBNull.Value)
                                model.PayMoney = Convert.ToDecimal(reader["PayMoney"]);
                            if (reader["SCategoryId"] != DBNull.Value)
                                model.SCategoryId = new Guid(reader["SCategoryId"].ToString());
                            model.SCategoryName = reader["SCategoryName"] == obj ? null : Convert.ToString(reader["SCategoryName"]);
                            model.SettleNo = reader["SettleNo"] == obj ? null : Convert.ToString(reader["SettleNo"]);
                            model.Remark = reader["Remark"] == obj ? null : Convert.ToString(reader["Remark"]);
                            list.Add(model);
                        }
                    }
                }
                catch (Exception ex)
                {
                    EventsLog.WriteLog("ErrorInfo" + ex.Message);
                }
            }
            return list;
        }

        public bool ModifyInitPay(InitPayEntity model)
        {
            var result = false;
            var strSql = new StringBuilder();
            strSql.Append(" UPDATE [PSS_InitPay] SET [SinglePaymentNo] = @SinglePaymentNo,[SinglePaymentDate] = @SinglePaymentDate,[VendorId] = @VendorId,[Remark] = @Remark ");
            strSql.Append(" WHERE [InitPayId] = @InitPayId ");
            using (var cmd = Db.GetSqlStringCommond(strSql.ToString()))
            {
                try
                {
                    Db.AddInParameter(cmd, "@SinglePaymentNo", model.SinglePaymentNo);
                    Db.AddInParameter(cmd, "@VendorId", model.VendorId);
                    Db.AddInParameter(cmd, "@SinglePaymentDate", model.SinglePaymentDate);
                    Db.AddInParameter(cmd, "@Remark", model.Remark);
                    Db.AddInParameter(cmd, "@InitPayId", model.InitPayId);
                    result = Db.ExecuteNonQuery(cmd) > 0;
                }
                catch (Exception ex)
                {
                    EventsLog.WriteLog("ErrorInfo" + ex.Message);
                }
            }
            return result;
        }

        public bool RemoveInitPay(string id)
        {
            var result = false;
            var strSql = new StringBuilder();
            strSql.Append(" DELETE FROM [PSS_InitPay] WHERE InitPayId=@InitPayId ");
            using (var cmd = Db.GetSqlStringCommond(strSql.ToString()))
            {
                try
                {
                    Db.AddInParameter(cmd, "@InitPayId", id);
                    if (Db.ExecuteNonQuery(cmd) > 0)
                    {
                        result = true;
                    }
                }
                catch (Exception ex)
                {
                    EventsLog.WriteLog("ErrorInfo" + ex.Message);
                }
            }
            return result;
        }

        public bool RemoveInitPayDetail(string id)
        {
            var result = false;
            var strSql = new StringBuilder();
            strSql.Append(" DELETE FROM [PSS_InitPayDetail] WHERE InitPayId=@InitPayId ");
            using (var cmd = Db.GetSqlStringCommond(strSql.ToString()))
            {
                try
                {
                    Db.AddInParameter(cmd, "@InitPayId", id);
                    if (Db.ExecuteNonQuery(cmd) > 0)
                    {
                        result = true;
                    }
                }
                catch (Exception ex)
                {
                    EventsLog.WriteLog("ErrorInfo" + ex.Message);
                }
            }
            return result;
        }
    }
}
